﻿using System;
using System.IO;

namespace Pay.Core {
	public class FileValid {
		/// <summary>
		/// 读取文件的真类型
		/// </summary>
		/// <param name="st"></param>
		/// <returns></returns>
		public static FileExtension GetFileType(byte[] file_byte) {
			FileExtension ext = FileExtension.None;
			string str = "";
			try {
				str = file_byte[0].ToString();
				str += file_byte[1].ToString();
				ext = (FileExtension)Enum.Parse(typeof(FileExtension), str);
			} catch {
			}
			return ext;
		}

		public static FileExtension GetFileType(Stream stream) {
			FileExtension ext = FileExtension.None;
			BinaryReader r = new BinaryReader(stream);
			string fileclass = "";
			byte buffer;
			try {
				buffer = r.ReadByte();
				fileclass = buffer.ToString();
				buffer = r.ReadByte();
				fileclass += buffer.ToString();
				ext = (FileExtension)Enum.Parse(typeof(FileExtension), fileclass);
			} catch {
			}
			return ext;
		}
		/// <summary>
		/// 将 Stream 转成 byte[]
		/// </summary>
		/// <returns>The to bytes.</returns>
		/// <param name="stream">Stream.</param>
		public static byte[] StreamToBytes(Stream stream) {
			byte[] bytes = new byte[stream.Length];
			stream.Read(bytes, 0, bytes.Length);
			// 设置当前流的位置为流的开始
			stream.Seek(0, SeekOrigin.Begin);
			return bytes;
		}

		/// <summary>
		/// 将 byte[] 转成 Stream
		/// </summary>
		/// <returns>The to stream.</returns>
		/// <param name="bytes">Bytes.</param>
		public static Stream BytesToStream(byte[] bytes) {
			Stream stream = new MemoryStream(bytes);
			return stream;
		}
	}
}
